package com.ktjy;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicQueueProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/T384");
        //创建连接对象
        Connection connection = factory.newConnection();
        //创建信道对象
        Channel channel = connection.createChannel();

        //定义交换机
        String exchangeName="topic_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false,false,null);
        //定义一个队列
        String urlComQueue="url_com_queue";
        channel.queueDeclare(urlComQueue,true,false,false,null);
        String urlXXXQueue="url_xxx_queue";
        channel.queueDeclare(urlXXXQueue,true,false,false,null);
        String urlKtjyQueue="url_ktjy_queue";
        channel.queueDeclare(urlKtjyQueue,true,false,false,null);

        //3.绑定队列和交换机
        channel.queueBind(urlComQueue,exchangeName,"#.com");
        channel.queueBind(urlXXXQueue,exchangeName,"#.xxx.*");
        channel.queueBind(urlKtjyQueue,exchangeName,"#.ktjy.#");


        //发信息
        String msg="hello world【#.com】";
        channel.basicPublish(exchangeName,"http://www.baidu.com",null,msg.getBytes());

        msg="hello world【#.xxx.*】";
        channel.basicPublish(exchangeName,"http://www.xxx.com",null,msg.getBytes());

        msg="hello world【#.ktjy.#】";
        channel.basicPublish(exchangeName,"http://www.ktjy.com",null,msg.getBytes());

        System.out.println("消息发送成功");

        //关闭信道和连接对象
        channel.close();
        connection.close();
    }
}
